package com.atguigui.leetcode;

/**
 * 592.分数加减运算
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/7/27 8:55
 */
public class P592FractionAdditionAndSubtraction {
    public static void main(String[] args) {
        Solution solution = new P592FractionAdditionAndSubtraction().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 模拟
         *
         * @param expression
         * @return
         */
        public String fractionAddition(String expression) {
            long denominator = 0, numerator = 1; // 分子，分母
            int index = 0, n = expression.length();
            while (index < n) {
                // 读取分子
                long denominator1 = 0, sign = 1;
                if (expression.charAt(index) == '-' || expression.charAt(index) == '+') {
                    //判断+和-
                    sign = expression.charAt(index) == '-' ? -1 : 1;
                    index++;
                }
                //确定指定的字符是否为数字
                while (index < n && Character.isDigit(expression.charAt(index))) {
                    //还原数字大小
                    denominator1 = denominator1 * 10 + expression.charAt(index) - '0';
                    index++;
                }
                denominator1 = sign * denominator1;
                //去掉'/'号
                index++;

                // 读取分母
                long numerator1 = 0;
                while (index < n && Character.isDigit(expression.charAt(index))) {
                    numerator1 = numerator1 * 10 + expression.charAt(index) - '0';
                    index++;
                }

                denominator = denominator * numerator1 + denominator1 * numerator;
                numerator *= numerator1;
            }
            if (denominator == 0) {
                return "0/1";
            }
            long g = gcd(Math.abs(denominator), numerator); // 获取最大公约数
            return denominator / g + "/" + numerator / g;
        }

        public long gcd(long a, long b) {
            long remainder = a % b;
            while (remainder != 0) {
                a = b;
                b = remainder;
                remainder = a % b;
            }
            return b;
        }
    }
}
